<template>
    <div class="sys-user-center-container">
        <a-row :gutter="5" style="width: 100%">
            <a-col :span="8">
                <a-card hoverable class="w-full flex flex-col items-center p-4">
                    <div class="text-center mb-6">
                        <a-avatar @click="handleChangeAvatar" :src="`/${userInfosState.userInfos.avatar}`" :size="100"
                            class="cursor-pointer hover:opacity-80 transition-all duration-300" />
                        <div class="mt-4 text-lg font-medium">{{ userInfosState.userInfos.realName }}</div>
                    </div>
                    <div class="w-full space-y-3">
                        <p class="flex items-center">
                            <bank-outlined class="mr-2" />
                            <span>{{ userInfosState.userInfos.orgName ?? "超级管理员" }}</span>
                        </p>
                        <p class="flex items-center">
                            <coffee-outlined class="mr-2" />
                            <span>{{ userInfosState.userInfos.posName ?? '超级管理员' }}</span>
                        </p>
                        <p class="flex items-center">
                            <environment-outlined class="mr-2" />
                            <span>{{ userInfosState.userInfos.address ?? '家庭住址' }}</span>
                        </p>
                    </div>
                    <div class="w-full h-15 my-4">
                        <a-image width="100%" :height="200" :src="`/${userInfosState.userInfos.signature}`"
                            fallback="" />
                    </div>
                    <div class="flex gap-3">
                        <a-button type="primary" @click="state.isShowSignature = true">
                            <template #icon><edit-outlined /></template>
                            电子签名
                        </a-button>
                        <input ref="fileRef" type="file" accept="image/png" style="display: none;" @change="fileChange">
                        <a-button @click="clickFile">
                            <template #icon><upload-outlined /></template>
                            上传签名
                        </a-button>
                    </div>
                </a-card>
            </a-col>
            <a-col :span="16">
                <a-card style="width: 100%" hoverable>
                    <a-tabs v-model:activeKey="state.activeKey">
                        <a-tab-pane key="1" tab="基础信息">
                            <a-form :model="state.ruleFormBase" ref="ruleFormBaseRef" :label-col="{ span: 6 }"
                                :wrapper-col="{ span: 18 }">
                                <a-row :gutter="35">
                                    <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                        <a-form-item label="真实姓名" name="realName"
                                            :rules="[{ required: true, message: '真实姓名不能为空' }]">
                                            <a-input v-model:value="state.ruleFormBase.realName" placeholder="真实姓名"
                                                allow-clear />
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                        <a-form-item label="昵称" name="nickName">
                                            <a-input v-model:value="state.ruleFormBase.nickName" placeholder="昵称"
                                                allow-clear />
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                        <a-form-item label="手机号码" name="phone"
                                            :rules="[{ required: true, message: '手机号码不能为空' }]">
                                            <a-input v-model:value="state.ruleFormBase.phone" placeholder="手机号码"
                                                allow-clear />
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                        <a-form-item label="邮箱" name="email">
                                            <a-input v-model:value="state.ruleFormBase.email" placeholder="邮箱"
                                                allow-clear />
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                        <a-form-item label="出生日期" name="birthday"
                                            :rules="[{ required: true, message: '出生日期不能为空' }]">
                                            <a-date-picker v-model:value="state.ruleFormBase.birthday" class="w-full"
                                                format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="出生日期" />
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                        <a-form-item label="性别" name="sex">
                                            <a-radio-group v-model:value="state.ruleFormBase.sex">
                                                <a-radio :value="1">男</a-radio>
                                                <a-radio :value="2">女</a-radio>
                                            </a-radio-group>
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                                        <a-form-item label="地址" name="address">
                                            <a-textarea v-model:value="state.ruleFormBase.address" placeholder="地址"
                                                allow-clear />
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                                        <a-form-item label="备注" name="remark">
                                            <a-textarea v-model:value="state.ruleFormBase.remark" placeholder="备注"
                                                allow-clear />
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                                        <a-form-item :wrapper-col="{ span: 24 }">
                                            <a-button type="primary" v-auth="'sysUser:baseInfo'"
                                                @click="submitUserBase">
                                                <template #icon><check-outlined /></template>
                                                保存基本信息
                                            </a-button>
                                        </a-form-item>
                                    </a-col>
                                </a-row>
                            </a-form>
                        </a-tab-pane>
                        <a-tab-pane key="3" tab="修改密码">
                            <a-form ref="ruleFormPasswordRef" :model="state.ruleFormPassword" :label-col="{ span: 3 }"
                                :wrapper-col="{ span: 21 }">
                                <a-form-item label="当前密码" name="passwordOld"
                                    :rules="[{ required: true, message: '当前密码不能为空' }]">
                                    <a-input-password v-model:value="state.ruleFormPassword.passwordOld"
                                        autocomplete="off" />
                                </a-form-item>

                                <a-form-item label="新密码" name="passwordNew"
                                    :rules="[{ required: true, message: '新密码不能为空' }]">
                                    <a-input-password v-model:value="state.ruleFormPassword.passwordNew"
                                        autocomplete="off" />
                                </a-form-item>

                                <a-form-item label="确认密码" name="passwordNew2"
                                    :rules="[{ required: true, validator: validatePassword ,trigger: 'blur'}]">
                                    <a-input-password v-model:value="state.passwordNew2" autocomplete="off" />
                                </a-form-item>

                                <a-form-item :wrapper-col="{ span: 24 }">
                                    <a-button @click="resetPassword">
                                        <template #icon><redo-outlined /></template>
                                        重置
                                    </a-button>
                                    <a-button type="primary" v-auth="'sysUser:changePwd'" @click="submitPassword"
                                        style="margin-left: 8px;">
                                        <template #icon><check-outlined /></template>
                                        确定
                                    </a-button>
                                </a-form-item>
                            </a-form>
                        </a-tab-pane>
                    </a-tabs>
                </a-card>
            </a-col>
        </a-row>
        <a-modal v-model:open="state.isShowSignature" title="电子签名">
            <VueSignaturePad ref="signaturePadRef" :options="state.signOptions"
                style="background-color: #fff;height: 250px;width: 100%;border: 1px dashed gray;" />
            <template #footer>
                <a-button @click="unDoSign">撤销</a-button>
                <a-button @click="clearSign">清屏</a-button>
                <a-button type="primary" :loading="state.loading" @click="handleSignatureOk">提交</a-button>
            </template>
        </a-modal>
        <cropper-dialog ref="cropperDialogRef" @upload-cropper-img="uploadCropperImg" />
    </div>
</template>

<script setup lang="ts" name="sysUserCenter">
import { h, onMounted, reactive, ref } from 'vue';
import { useUserInfo } from '@/stores/userInfo';
import { storeToRefs } from 'pinia';
import { apiSysFileUploadAvatarPostForm, apiSysFileUploadSignaturePostForm } from '@/api/sys/syfFile';
import type { ResType } from '@/api/types';
import type { SysFileType, SysUserBaseInfoType } from './types';
import { apiSysUserBaseInfoGet, apiSysUserBaseInfoPost, apiSysUserChangePwdPost } from '@/api/sys/apiUser';
import { base64ToFile, blobToFile } from '@/utils';
import cropperDialog from './components/cropperDialog.vue';
import type { FormInstance } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
// import { sm2 } from 'sm-crypto-v2';
import {sm2} from 'sm-crypto'
import { notification ,Button } from 'ant-design-vue';
import { clearAccessAfterReload } from '@/api/request';

defineOptions({
    name: "sysUserCenter"
})

const ruleFormPasswordRef = ref<FormInstance>()
const ruleFormBaseRef = ref<FormInstance>()
const cropperDialogRef = ref<InstanceType<typeof cropperDialog>>()
const signaturePadRef = ref()
const fileRef = ref<HTMLInputElement | null>()
const userInfosStore = useUserInfo()
const { state: userInfosState } = storeToRefs(userInfosStore)

const state = reactive({
    activeKey: "1",
    ruleFormBase: {
        signature: ""
    } as SysUserBaseInfoType,
    ruleFormPassword:{}as any,
    loading: false,
    isShowSignature: false,
    signOptions: { //签名配置
        penColor: '#000000',
        minWidth: 1.0,
        onBegin: () => {
            signaturePadRef.value.resizeCanvas();
        },
    },
    passwordNew2:""
})

const clickFile = () => {
    fileRef.value?.click()
}

const fileChange = async (e: Event) => {
    const target = e.target as HTMLInputElement
    const file = target.files?.[0]
    const res = await apiSysFileUploadSignaturePostForm(file) as ResType<SysFileType>
    userInfosState.value.userInfos.signature = res.data.result.url
    state.ruleFormBase.signature = res.data.result.url
}

const handleSignatureOk = async () => {
    const { isEmpty, data } = signaturePadRef.value.saveSignature();
    // data是base64格式
    if (isEmpty) {
        userInfosState.value.userInfos.signature = null
        state.ruleFormBase.signature = null
    } else {
        const file = base64ToFile(data, userInfosState.value.userInfos.account + '.png')
        const res = await apiSysFileUploadSignaturePostForm(file) as ResType<SysFileType>

        userInfosState.value.userInfos.signature = res.data.result.url
        state.ruleFormBase.signature = res.data.result.url
    }
    clearSign();
    handleSignatureClose();
}

const handleSignatureClose = () => {
    state.isShowSignature = false
}

const unDoSign = () => {
    signaturePadRef.value.undoSignature();
}
const clearSign = () => {
    signaturePadRef.value.clearSignature();
}

const handleChangeAvatar = () => {
    cropperDialogRef.value?.handleOpen()
}

const uploadCropperImg = async (blob: Blob) => {
    const file = blobToFile(blob, userInfosState.value.userInfos.account + '.png')
    const res = await apiSysFileUploadAvatarPostForm(file) as ResType<SysFileType>

    userInfosState.value.userInfos.avatar = res.data.result.url
    state.ruleFormBase.avatar = res.data.result.url

}

const submitUserBase = async () => {
    await ruleFormBaseRef.value?.validate()
    await apiSysUserBaseInfoPost(state.ruleFormBase)
    await initForm()
}

const initForm = async () => {
    state.loading = true
    const res = await apiSysUserBaseInfoGet() as ResType<SysUserBaseInfoType>
    state.ruleFormBase = res.data.result ?? { account: '' } //赋值表单数据
    state.loading = false
}
const validatePassword = async (rule: Rule, value: string) => {
    if (state.passwordNew2 !== state.ruleFormPassword.passwordNew) {
        return Promise.reject('两次输入密码不一致!');
    } else {
        return Promise.resolve();
    }
}

const submitPassword = async () => {
    await ruleFormPasswordRef.value?.validate()
    const cpwd = {  passwordOld: '', passwordNew: ''} 
    const publicKey = import.meta.env.VITE_SM_PUBLIC_KEY
    cpwd.passwordOld = sm2.doEncrypt(state.ruleFormPassword.passwordOld, publicKey, 1);
    cpwd.passwordNew = sm2.doEncrypt(state.ruleFormPassword.passwordNew, publicKey, 1);
    await apiSysUserChangePwdPost(cpwd)

    const key = `open${Date.now()}`;
    notification.open({
        message: '修改提示',
        description:
        '推荐请重新登录.',
        duration: 0,
        btn: () =>
        h(
            Button,
            {
            type: 'primary',
            size: 'small',
            onClick: () => {
                notification.close(key)
                clearAccessAfterReload()
            },
            },
            { default: () => '确定' },
        ),
        key,
    });
}

const resetPassword =()=>{
	state.ruleFormPassword.passwordOld = '';
	state.ruleFormPassword.passwordNew = '';
	state.passwordNew2 = '';
}

onMounted(async () => {
    initForm()
})
</script>

<style lang="scss" scoped>
:deep(.ant-btn >span) {
    display: inline-flex !important;
}

:deep(.ant-card-body) {
    width: 100%;
}
</style>